<template>
  <div>
  <el-dialog width="600px" @close="handleCancel()" title="编辑用户" :visible.sync="dialogVisible">
  <div class="user-edit-container">
    <!-- <el-card> -->
      <!-- <div slot="header" class="clearfix">
        <span>编辑用户</span>
        <el-button @click="handleCancel" class="cancel-btn">返回</el-button>
      </div> -->

      <el-form ref="userForm" :model="userForm" :rules="userRules" label-width="120px" class="user-form">
        <el-form-item label="用户ID" prop="id">
          <el-input v-model="userForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱地址"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="userForm.role">
            <el-radio label="admin">管理员</el-radio>
            <el-radio label="user">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="userForm.avatar" :src="imgUrl + userForm.avatar" class="avatar" />  
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="avatar-tip">支持jpg/png格式，文件大小不超过2MB</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    <!-- </el-card> -->
  </div>
  </el-dialog>
  </div>
</template>

<script>
import { updateUser } from '@/api/users'
import { uploadImage, deleteImage } from '@/api/auth'

export default {
  name: 'UserEdit',
  data () {
    return {
      dialogVisible: false,
      userId: this.$route.params.id,
      userForm: {
        id: '',
        username: '',
        email: '',
        phone: '',
        role: 'user',
        status: "1",
        avatar: ''
      },
      userRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      loading: false,
      uploadUrl: 'http://localhost:5010/api/upload/single',
      imgUrl: this.$imgUrl
    }
  },
  mounted () {
    
  },
  methods: {
    openDialog (row) {
      this.loading = true
      this.dialogVisible = true
      let newForm = { ...row };
      newForm.id = newForm._id;
      delete newForm._id; 
      delete newForm.createdAt;
      delete newForm.updatedAt;
      delete newForm.__v; 
      this.userForm = { ...newForm };
      setTimeout(() => {
        this.loading = false
      }, 500)
    },
    handleSubmit () {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          this.loading = true
          updateUser(this.userForm).then(res => {
            if (res.errCode == 0) {
              this.loading = false
              this.$message.success('编辑成功')
              this.dialogVisible = false;
              this.$emit('initList')
            } else {
              this.loading = false
              this.$message.error(res.errMsg)
            }
          })
        } else {
          this.$message.error('请检查表单信息')
          return false
        }
      })
    },
    handleCancel () {
      this.userForm = {
        id: '',
        username: '',
        password: '',
        email: '',
        phone: '',
        role: 'user',
        status: 1,
        avatar: ''
      };
      this.dialogVisible = false;
    },
    handleAvatarSuccess (res, file, fileList) {
      // 模拟上传成功后的处理
      console.log("上传成功", res,file)
      this.userForm.avatar = res.data.url;
      // this.userForm.avatar = URL.createObjectURL(file.raw)
      this.$message.success('上传成功')
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss" scoped>
.user-edit-container {
  width: 100%;
  height: 100%;
  overflow: auto;
}

.cancel-btn {
  float: right;
}

.user-form {
  padding: 20px 0;
}

.avatar-uploader {
  margin-top: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}

.avatar {
  width: 148px;
  height: 148px;
  display: block;
}

.avatar-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}
</style>
